package tencent

import (
	"context"

	"gitee.com/go-course/go9/projects/devcloud/cmdb/apps/resource"
	"gitee.com/go-course/go9/projects/devcloud/cmdb/common/logger"
	"github.com/alibabacloud-go/tea/tea"
	lighthouse "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lighthouse/v20200324"
)

// 需要返回的数据是什么？  采用回调(避免使用channel) js  array.forEatch(() => {})
// 如何实现分页?
// 限速如何处理?
func (c *TencentClient) SyncHost(ctx context.Context) {
	client, err := c.lighthouse()
	if err != nil {
		return
	}

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := lighthouse.NewDescribeInstancesRequest()
	request.Limit = &c.pageSize

PAGE_QUERY:
	// 返回的resp是一个DescribeInstancesResponse的实例，与请求对象对应
	response, err := client.DescribeInstances(request)
	if err != nil {
		logger.L().Error().Msgf("sync instance error, %s", err)
		return
	}

	// 转化成cmdb resoruce
	for i := range response.Response.InstanceSet {
		item := response.Response.InstanceSet[i]
		r := c.TransferLighthouseInstance(item)
		// 调用hook交给hook处理
		// go wait group
		c.hook(ctx, r)
	}

	// 判断这一页是不是满的
	if len(response.Response.InstanceSet) == int(c.pageSize) {
		// 等待一个可用的限速Token 才去访问Server
		c.tb.Wait(1)
		// 到下一页
		*request.Limit++
		goto PAGE_QUERY
	}
}

// 这个函数专门处理转换
func (c *TencentClient) TransferLighthouseInstance(
	ins *lighthouse.Instance) *resource.Resource {
	r := resource.NewResource()
	r.Meta.Id = tea.StringValue(ins.InstanceId)
	r.Spec.Extra["bundle_id"] = tea.StringValue(ins.BundleId)
	r.Spec.Extra["blueprint_id"] = tea.StringValue(ins.BlueprintId)

	r.Spec.Cpu = int32(tea.Int64Value(ins.CPU))
	r.Spec.Memory = int32(tea.Int64Value(ins.Memory) * 1024)
	r.Spec.Name = tea.StringValue(ins.InstanceName)
	r.Cost.PayModeDetail = tea.StringValue(ins.InstanceChargeType)
	r.Status.Phase = tea.StringValue(ins.InstanceState)
	r.Status.PrivateAddress = tea.StringSliceValue(ins.PrivateAddresses)
	r.Status.PublicAddress = tea.StringSliceValue(ins.PublicAddresses)
	return r
}
